import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import WangEditor from "@/components/WangEditor";
import { ProForm, ProFormInstance } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, message } from "antd";
import { useEffect, useRef } from "react";

interface Props {
	getDataApi?: any;
	saveApi?: any;
	name?: string;
	btnStyles?: any;
}

export default (props: Props) => {
	const { getDataApi, saveApi, name, btnStyles } = props;
	const { loading, runAsync, data } = useRequest(getDataApi, { manual: true });
	const { loading: saveLoading, runAsync: saveRunAsync } = useRequest(saveApi, { manual: true });
	const formRef = useRef<ProFormInstance>();

	useEffect(() => {
		runAsync().then((res: any) => {
			formRef.current?.setFieldsValue(res?.data);
		});
	}, []);

	const handleSubmit = () => {
		formRef.current?.validateFieldsReturnFormatValue?.().then(values => {
			if (data?.data?.[name] === values?.[name]) return message.success("保存成功");
			saveRunAsync(values).then((res: any) => {
				if (res?.code === RESULT_CODES.SUCCESS) {
					message.success("保存成功");
				}
			});
		});
	};

	return (
		<Loading isHeight100 loading={loading || saveLoading}>
			<ProForm formRef={formRef} submitter={false} style={{ height: "100%" }}>
				<ProForm.Item name={name} rules={[{ required: true, message: "请输入内容" }]} style={{ height: "100%" }}>
					<WangEditor />
				</ProForm.Item>
				<div style={{ padding: "24px", display: "flex", justifyContent: "center", ...btnStyles }}>
					<Button type="primary" onClick={handleSubmit}>
						保存
					</Button>
				</div>
			</ProForm>
		</Loading>
	);
};
